package org.batatasframework.web.ui;

import java.util.ArrayList;
import java.util.List;

import org.batatasframework.web.element.Table;
import org.batatasframework.web.element.TableBody;
import org.batatasframework.web.element.TableTd;
import org.batatasframework.web.element.TableTr;
import org.springframework.ui.Model;
import org.springframework.web.servlet.ModelAndView;


/**
 * 一个可编辑的表单
 * @author jackson
 *
 */
public class FormObject {
	
	private final List<FormCell> cells = new ArrayList<>();
	
	public void addCell(FormCell cell){
		this.cells.add(cell);
	}
	
	public void appendTo(Model model){
		for(FormCell cell : cells){
			model.addAttribute(cell.getKey(), cell);
		}
	}
	
	public void appendTo(ModelAndView mav){
		for(FormCell cell : cells){
			mav.addObject(cell.getKey(), cell);
		}
	}
	
	public void render(Table table, int columnSize){
		TableBody body = table.currentElement();
		int rowIndex = 0, colIndex = 0;
		int maxCol = columnSize * 2;
		for(FormCell cell : cells){
			if(maxCol >= colIndex){
				colIndex = 0;
				rowIndex++;
				//下一行了
			}
			
			TableTr tr = body.indexOf(rowIndex);
			cell.render(tr);
			colIndex = tr.size();
			
			int rowspan = cell.getRowspan();
			int colspan = cell.getColspan();
			for(int i = 1; i < rowspan;i++){
				int skipRowIndex = i + rowIndex;
				int nullColsize = colspan > 1 ? colspan * 2 : 2;
				
				TableTr ttr = body.indexOf(skipRowIndex);
				for(int j = 0; j < nullColsize; j++){
					ttr.addElement(TableTd.SKIP);
				}
			}
			
		}
	}
}
